import Taro from '@tarojs/taro'
import {getToken} from './auth'

// 使用 Taro 的环境变量
declare const process: {
  env: {
    TARO_APP_API_URL?: string
  }
}

const API_URL = process.env.TARO_APP_API_URL || 'http://localhost:3000/api'

interface RequestOptions {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  data?: any
  needAuth?: boolean
}

interface ApiResponse<T = any> {
  success: boolean
  data?: T
  error?: string
}

export async function request<T = any>(options: RequestOptions): Promise<ApiResponse<T>> {
  const {url, method = 'GET', data, needAuth = false} = options

  const headers: any = {
    'Content-Type': 'application/json'
  }

  // 如果需要认证，添加 token
  if (needAuth) {
    const token = getToken()
    if (token) {
      headers.Authorization = `Bearer ${token}`
    }
  }

  try {
    const response = await Taro.request({
      url: `${API_URL}${url}`,
      method,
      data,
      header: headers
    })

    if (response.statusCode === 200 || response.statusCode === 201) {
      return response.data as ApiResponse<T>
    } else if (response.statusCode === 401) {
      // token 过期或无效，跳转到登录页
      Taro.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        Taro.navigateTo({url: '/pages/login/index'})
      }, 1500)
      return {
        success: false,
        error: '请先登录'
      }
    } else {
      const errorData = response.data as ApiResponse
      return {
        success: false,
        error: errorData.error || '请求失败'
      }
    }
  } catch (error: any) {
    console.error('请求错误:', error)
    return {
      success: false,
      error: error.errMsg || '网络请求失败'
    }
  }
}
